package com.bys.admin.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.bys.admin.system.entity.SysDept;
import com.bys.admin.system.entity.SysUser;
import com.bys.admin.system.mapper.SysUserMapper;
import com.bys.admin.system.controller.vo.SysUserVo;
import com.bys.admin.system.service.ISysDeptService;
import com.bys.admin.system.service.ISysUserService;
import com.github.yulichang.base.MPJBaseServiceImpl;
import com.github.yulichang.wrapper.MPJLambdaWrapper;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import jakarta.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author bys
 * @since 2023-06-26
 */
@Service
public class SysUserServiceImpl extends MPJBaseServiceImpl<SysUserMapper, SysUser> implements ISysUserService {

    @Resource
    private ISysDeptService sysDeptService;
    @Override
    public Page<SysUserVo> loadPageVo(Page<SysUserVo> page) {
        Page<SysUserVo> sysUserVoPage = selectJoinListPage(page, SysUserVo.class, new MPJLambdaWrapper<SysUser>());
        List<SysUserVo> sysUserVos = sysUserVoPage.getRecords();
        List<Long> deptIds = sysUserVos.stream().map(SysUserVo::getDeptId).distinct().collect(Collectors.toList());
        List<SysDept> sysDepts;
        if(!CollectionUtils.isEmpty(deptIds)){
            sysDepts = sysDeptService.listByIds(deptIds);
        } else {
            sysDepts = new ArrayList<>();
        }
        sysUserVos.forEach(user ->{
            SysDept sysDept = sysDepts.stream().filter(dept -> dept.getId().equals(user.getDeptId())).findFirst().orElse(null);
            if(Objects.nonNull(sysDept)){
                user.setDeptName(sysDept.getDeptName());
            }
        });
        return sysUserVoPage;
    }

    @Override
    public SysUser getUserByUsername(String username) {
        return getOne(new LambdaQueryWrapper<SysUser>().eq(SysUser::getUserName, username), false);
    }
}
